import axios, { AxiosRequestConfig } from "axios"
import Router from "@/router/index"
import Utils from '@/utils/Utils';

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
axios.defaults.headers['Access-Control-Allow-Origin'] = true
// 创建axios实例
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    // 超时
    timeout: 10000
})

// request拦截器
service.interceptors.request.use(
    config => {
        const token = Utils.getLocal(Constant.LOGIN_TOKEN_KEY)?.token || ""
        if (token) {
            config.headers['Authorization'] = 'Bearer ' + token // 让每个请求携带自定义token 请根据实际情况自行修改
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    res => {
        return Promise.resolve(res.data)
    },
    error => {
        const e = error.response || {}
        const result = e.data
        if (result.code === 401) {
            localStorage.removeItem(Constant.LOGIN_TOKEN_KEY)
            return Router.replace('/login')
        }
        return Promise.reject(result)
    }
)

// 对象转Map
export const obj2Map = (obj: any): Map<string, any> => {
    let params = new Map();
    for (var key in obj) {
        params.set(key, obj[key]);
    }
    return params;
}
// Map格式化Get请求参数
export const getParams = (map: any): string => {
    let params = '';
    for (let key of map) {
        params += '&' + key[0] + '=' + key[1];
    }
    return params.replace('&', '?');
}

export const GET = (url: string, data: object, config?: AxiosRequestConfig): Promise<Array<any>> =>
    new Promise(async resolve => {
        url += getParams(obj2Map(data))
        try {
            const res = await service.get(url, config)
            resolve([undefined, res])
        } catch (err) {
            resolve([err, undefined])
        }
    })

export const POST = (url: string, data?: any, config?: AxiosRequestConfig): Promise<Array<any>> =>
    new Promise(resolve =>
        service.post(url, data, config).then(res => {
            resolve([undefined, res])
        }).catch(err => {
            resolve([err, undefined])
        })
    )

export const DELETE = (url: string, config?: AxiosRequestConfig): Promise<Array<any>> =>
    new Promise(async resolve => {
        try {
            const res = await service.delete(url, config)
            resolve([undefined, res])
        } catch (err) {
            resolve([err, undefined])
        }
    })

export const PATCH = (url: string, data?: any, config?: AxiosRequestConfig): Promise<Array<any>> =>
    new Promise(async resolve => {
        try {
            const res = await service.patch(url, data, config)
            resolve([undefined, res])
        } catch (err) {
            resolve([err, undefined])
        }
    })

export default service
